package com.sanley.piss.web.service;

import com.sanley.piss.mapper.*;
import com.sanley.piss.model.ServiceImpl;
import com.sanley.piss.model.StringUtil;
import com.sanley.piss.model.exceptionUtil.exception.ServiceException;
import com.sanley.piss.model.exceptionUtil.json.ResultEnum;
import com.sanley.piss.model.po.User;
import com.sanley.piss.model.po.UserAndRoleRelation;
import com.sanley.piss.model.vo.UserVO;
import com.sanley.piss.web.service.mapper.IUserService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * Create By  on 2021/3/17.
 *
 * @author 张凯大天才
 */
@Service
@Primary
@Transactional(rollbackFor = ServiceException.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private Logger logger = LoggerFactory.getLogger("UserServiceImpl");

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserAndRoleRelationMapper userAndRoleRelationMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private DictionaryDataMapper dictionaryDataMapper;


    /**
     * 添加用户
     *
     * @param user 从前端获取的数据 包括权限名称以及角色名称 角色查询方法 List<Map<Integer,String>> selectAllRole();
     *             name=user.roleIds
     */
    @Override
    public void insert(UserVO user) {
        String salt = UUID.randomUUID().toString().toUpperCase();
        SimpleHash simpleHash = new SimpleHash("MD5", user.getPassword(), salt, 5);
        //查询用户名是否重复
        if (StringUtil.isNotNull(baseMapper.getUserByUsername(user.getUsername()))) {
            throw new ServiceException(ResultEnum.userExist);
        }
        /**
         * 查看是否有重复部门
         */


        //插入部门ID
        user.setDeptId(user.getOrganization().getId());
        user.setPassword(simpleHash.toString());
        user.setSalt(salt);
        user.setState(Byte.valueOf("0"));

        LocalDateTime date = LocalDateTime.now();
        user.setGmtCreate(date);

        //执行插入 获取插入行ID
        baseMapper.insert(user);
        //从页面获取角色信息并写入关联表
        int insert = userAndRoleRelationMapper.insert(new UserAndRoleRelation(user.getId(), roleMapper.selectRoleIdByName("admin")));
        if (insert == 0) {
            throw new ServiceException(ResultEnum.roleIsNull);
        }
    }

    /**
     * 修改账号状态
     * 把state 的值改变 1变为2
     *
     * @param ids
     */
    @Override
    public void removeByIds(Integer[] ids) {
        baseMapper.updateSateById(ids, Byte.valueOf("3"));

    }

    /**
     * 修改密码
     */
    @Override
    public void updatePassword(String oldPassword, String newPassword, Integer id) {
        User user = baseMapper.selectById(id);
        if (StringUtil.isNull(user)) {
            throw new ServiceException(ResultEnum.userIsNull);
        }
        String salt = user.getSalt();
        SimpleHash oPassword = new SimpleHash("MD5", oldPassword, salt, 5);
        SimpleHash password = new SimpleHash("MD5", newPassword, salt, 5);
        if (!user.getPassword().equals(oPassword.toString())) {
            throw new ServiceException(ResultEnum.pwdError);
        }
        baseMapper.updatePasswordById(password.toString(), id);

    }

    /**
     * 重置密码
     */
    @Override
    public void roloadPassword(String newPassword, Integer userId) {
        User user = baseMapper.selectById(userId);
        if (StringUtil.isNull(user)) {
            throw new ServiceException(ResultEnum.userIsNull);
        }
        SimpleHash simpleHash = new SimpleHash("MD5", newPassword, user.getSalt(), 5);
        baseMapper.updatePasswordById(simpleHash.toString(), user.getId());
    }

    @Override
    public User selectById(Integer id) {
        User selectOne = baseMapper.selectById(id);
        if (StringUtil.isNull(selectOne)) {
            throw new ServiceException("信息不存在");
        }
        return selectOne;
    }

}
